package org.jay.angla.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.achartengine.GraphicalView;
import org.jay.angla.activity.MainActivity_;
import org.jay.angla.activity.QASettingActivity_;
import org.jay.angla.adapter.MultiSelectAdapter;
import org.jay.angla.adapter.MultiSelectAdapter.ViewHolder;
import org.jay.angla.base.QuantitativeAnalysisRecord;
import org.jay.angla.base.TimeScanningRecord;
import org.jay.angla.chart.QAChart;
import org.jay.angla.dialog.QANameDialog;
import org.jay.angla.dialog.QASampleDialog;
import org.jay.angla.dialog.RecordNameDialog;
import org.jay.angla.onlab.OnlabApplication;
import org.jay.angla.onlab.R;
import org.jay.angla.utils.Contants;
import org.jay.angla.utils.ToastShow;
import org.jay.angla.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

@SuppressLint("NewApi")
public class FragmentQuantitativeAnalysis extends Fragment implements
		View.OnClickListener {

	private FragmentCallbackListener mListener;
	private FrameLayout mQAChart;
	private QAChart mChart;
	private GraphicalView mChartView;

	private Button mStartButton;
	private Button mRezeroButton;

	private TextView mCalcTypeTextView;
	private TextView mFittingMethodTextView;
	private TextView mConcUnitTextView;

	private ListView mSampleListView;
	private MultiSelectAdapter mSampleAdapter;
	private List<HashMap<String, String>> mSampleData;
	private ListView mTestListView;
	private MultiSelectAdapter mTestAdapter;
	private List<HashMap<String, String>> mTestData;

	private TextView mFormaluTextView;
	private LinearLayout mSelectLayout;

	private int mRequestCode;
	private Intent mIntent;

	private ToastShow mToastShow;
	private QASampleDialog mSampleDialog;
	private QANameDialog mNameDialog;

	private float k0;
	private float k1;
	private float k2;
	private float k3;

	private boolean mIsRezeroed = false;
	private boolean mSelectMode = false;

	private Button mSelectAllButton;
	private Button mCancelButton;
	private Button mDeleteButton;

	private Button mSampleDoFittingButton;
	private Button mSampleAllSelectButton;
	private Button mSampleDeleteButton;

	private RecordNameDialog mDialog;
	private boolean loadHistory = false;
	private int historyId;

	private TextView mRValueTextView;
	private boolean isSampleDone = false;
	private float sampleA0;
	private float sampleA1;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		mListener = (FragmentCallbackListener) activity;
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(
				R.layout.fragment_quantitative_analysis, container, false);

		mQAChart = (FrameLayout) rootView.findViewById(R.id.chart_qa);
		mChart = new QAChart(getActivity());
		mChart.clear();
		mChartView = mChart.getChartView(getActivity());
		mQAChart.removeAllViews();
		mQAChart.addView(mChartView);

		mStartButton = (Button) rootView.findViewById(R.id.btn_start);
		mRezeroButton = (Button) rootView.findViewById(R.id.btn_rezero);
		mStartButton.setOnClickListener(this);
		mRezeroButton.setOnClickListener(this);

		mCalcTypeTextView = (TextView) rootView
				.findViewById(R.id.tv_qa_setting_biaodingfangshi);
		mFittingMethodTextView = (TextView) rootView
				.findViewById(R.id.tv_qa_setting_nihefangshi);
		mConcUnitTextView = (TextView) rootView
				.findViewById(R.id.tv_qa_setting_nongdudanwei);

		// listview
		mSampleListView = (ListView) rootView.findViewById(R.id.lv_qa_sample);
		mTestListView = (ListView) rootView.findViewById(R.id.lv_qa_test);
		mSampleData = new ArrayList<HashMap<String, String>>();
		mTestData = new ArrayList<HashMap<String, String>>();
		mSampleAdapter = new MultiSelectAdapter(getActivity(), mSampleData,
				R.layout.item_qa_sample, new String[] { "id", "name", "abs",
						"conc", }, new int[] { R.id.item_number,
						R.id.item_name, R.id.item_abs, R.id.item_conc });

		mTestAdapter = new MultiSelectAdapter(getActivity(), mTestData,
				R.layout.item_qa_sample, new String[] { "id", "name", "abs",
						"conc", }, new int[] { R.id.item_number,
						R.id.item_name, R.id.item_abs, R.id.item_conc });
		mSampleListView.setAdapter(mSampleAdapter);
		mTestListView.setAdapter(mTestAdapter);

		mSampleDialog = new QASampleDialog(getActivity());
		mSampleDialog.setOnClickListener(this);
		mNameDialog = new QANameDialog(getActivity());
		mNameDialog.setOnClickListener(this);
		mSampleListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int pos, long id) {
						// TODO Auto-generated method stub
						String name = "";
						String conc = "";

						HashMap<String, String> item;
						item = mSampleData.get(pos);
						name = item.get("name");
						conc = item.get("conc");

						mSampleDialog.show(pos, name, conc);
					}
				});

		mTestListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int pos, long id) {
						// TODO Auto-generated method stub
						if (mSelectMode) {
							ViewHolder holder = (ViewHolder) view.getTag();
							holder.cb.toggle();
							mTestAdapter.getIsSelected().put(pos,
									holder.cb.isChecked());
						} else {
							String name = "";
							HashMap<String, String> item;
							item = mTestData.get(pos);
							name = item.get("name");
							mNameDialog.show(pos, name);
						}
					}
				});

		mTestListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (!mSelectMode) {
					mSelectMode = true;
					mTestAdapter.setSelectMode(true);
					mTestAdapter.notifyDataSetInvalidated();
					mSelectLayout.setVisibility(View.VISIBLE);
					// prepare for operation ui
				}
				return true;
			}
		});

		mDialog = new RecordNameDialog(getActivity());
		mDialog.setOnClickListener(this);

		mFormaluTextView = (TextView) rootView.findViewById(R.id.tv_formalu);

		if (loadHistory) {
			List<String> namesList = OnlabApplication.getInstance()
					.getQuantitativeAnalusisDB().getTables();
			// load select record
			String recordname = namesList.get(historyId);
			List<QuantitativeAnalysisRecord> list = OnlabApplication
					.getInstance().getQuantitativeAnalusisDB()
					.getRecords(recordname);
			clearData();
			for (int i = 0; i < list.size(); i++) {
				QuantitativeAnalysisRecord record = list.get(i);
				addOneItem(record);
				// update chart
			}

		}

		mIntent = new Intent();
		mIntent.setClass(getActivity(), QASettingActivity_.class);
		mToastShow = new ToastShow(getActivity());
		if (!loadHistory) {
			mRequestCode = 0;
			startActivityForResult(mIntent, mRequestCode);
		}

		mIsRezeroed = false;
		mSelectMode = false;
		mSelectLayout = (LinearLayout) rootView
				.findViewById(R.id.layout_select);
		mSelectAllButton = (Button) rootView.findViewById(R.id.bt_select_all);
		mCancelButton = (Button) rootView.findViewById(R.id.bt_cancel);
		mDeleteButton = (Button) rootView.findViewById(R.id.bt_delete);
		mSampleDoFittingButton = (Button) rootView
				.findViewById(R.id.bt_do_fitting);
		mSampleAllSelectButton = (Button) rootView
				.findViewById(R.id.bt_sample_all_select);
		mSampleDeleteButton = (Button) rootView
				.findViewById(R.id.bt_sample_delete);
		mSelectAllButton.setOnClickListener(this);
		mCancelButton.setOnClickListener(this);
		mDeleteButton.setOnClickListener(this);
		mSampleDoFittingButton.setOnClickListener(this);
		mSampleAllSelectButton.setOnClickListener(this);
		mSampleDeleteButton.setOnClickListener(this);

		mRValueTextView = (TextView) rootView.findViewById(R.id.tv_r_value);
		mRValueTextView.setTextColor(Color.GREEN);
		isSampleDone = false;
		// if (!mIsRezeroed) {
		// mStartButton.setEnabled(false);
		// }

		return rootView;
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		((MainActivity_) getActivity()).setMainButtonsEnable();
		loadHistory = false;
	}

	public void loadHistoryById(int id) {
		loadHistory = true;
		historyId = id;
		if (isAdded()) {
			List<String> namesList = OnlabApplication.getInstance()
					.getQuantitativeAnalusisDB().getTables();
			// load select record
			String recordname = namesList.get(historyId);
			List<QuantitativeAnalysisRecord> list = OnlabApplication
					.getInstance().getQuantitativeAnalusisDB()
					.getRecords(recordname);
			clearData();
			for (int i = 0; i < list.size(); i++) {
				QuantitativeAnalysisRecord record = list.get(i);
				addOneItem(record);
				// update chart
			}
		}
	}

	public boolean isSelectMode() {
		return mSelectMode;
	}

	public void onBack() {
		mSelectMode = false;
		mTestAdapter.setSelectMode(false);
		mTestAdapter.notifyDataSetInvalidated();
		mSelectLayout.setVisibility(View.GONE);
	}

	private void clearData() {
		mTestData.clear();
		mTestAdapter.notifyDataSetChanged();
		mSampleData.clear();
		mSampleAdapter.notifyDataSetChanged();
	}

	void showAlertDialog(final int pos) {
		new AlertDialog.Builder(getActivity())
				.setTitle(getString(R.string.system_notice))
				.setMessage(getString(R.string.sure_to_delete))
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								removeOneItem(pos);
							}
						})
				.setNegativeButton(getString(R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {// 响应事件
								// TODO Auto-generated method stub
							}
						}).show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) {
		case QASettingActivity_.REQUEST_CODE_SURE:
			int fitting_method = data.getIntExtra("FITTING_METHOD",
					QASettingActivity_.FITTING_METHOD_ONE);
			int conc_unit = data.getIntExtra("CONC_UNIT",
					QASettingActivity_.CONCENTRATION_UNIT_UG_ML);
			int sample_number = data.getIntExtra("SAMPLE_NUMBER", 1);
			int wavelength_number = data.getIntExtra("WAVELENGTH", 1);
			int calc_type = data.getIntExtra("CALC_TYPE",
					QASettingActivity_.CALC_TYPE_SAMPLE);
			float k0 = data.getFloatExtra("K0", 1.00f);
			float k1 = data.getFloatExtra("K1", 1.00f);
			float k2 = data.getFloatExtra("K2", 1.00f);
			float k3 = data.getFloatExtra("K3", 1.00f);
			float wavelength1 = data.getFloatExtra("WAVELENGTH1", 600.00f);
			float wavelength2 = data.getFloatExtra("WAVELENGTH2", 600.00f);
			float wavelength3 = data.getFloatExtra("WAVELENGTH3", 600.00f);
			float ratio1 = data.getFloatExtra("RATIO1", 0.00f);
			float ratio2 = data.getFloatExtra("RATIO2", 0.00f);
			float ratio3 = data.getFloatExtra("RATIO3", 0.00f);

			prepareWithParam(fitting_method, conc_unit, calc_type,
					sample_number, wavelength_number, k0, k1, k2, k3,
					wavelength1, wavelength2, wavelength3, ratio1, ratio2,
					ratio3);
			if (wavelength_number == QASettingActivity_.WAVELENGTH_ONE) {
				// set wavelength
				((MainActivity_) getActivity()).setWL(wavelength1);
				((MainActivity_) getActivity()).showWavelengthReset();
			} else {
				mToastShow.toastShow("双波长法");
			}

			break;
		case QASettingActivity_.REQUEST_CODE_CANCEL:
			break;

		default:
			break;
		}
	}

	private void prepareWithParam(int fitting_method, int conc_unit,
			int calc_type, int sample_num, int wavelength_num, float k0,
			float k1, float k2, float k3, float wl1, float wl2, float wl3,
			float ratio1, float ratio2, float ratio3) {
		if (calc_type == QASettingActivity_.CALC_TYPE_SAMPLE) {
			mSampleListView.setVisibility(View.VISIBLE);
			mFormaluTextView.setVisibility(View.INVISIBLE);
			mSampleData.clear();
			mCalcTypeTextView.setText(getString(R.string.sample_fitting));
			int count = sample_num;
			if (mSampleData.size() == 0) {
				addEmptySample();
				mSampleAdapter.setSelectMode(true);
			}
			mChart.clear();
			mChartView.postInvalidate();
			// for (int i = 0; i < count; i++) {
			// HashMap<String, String> item = new HashMap<String, String>();
			// int index = mSampleData.size() + 1;
			// item.put("id", "" + index);
			// item.put("name", "");
			// item.put("abs", "");
			// item.put("conc", "");
			// mSampleData.add(item);
			// mSampleAdapter.notifyDataSetChanged();
			// }
		} else if (calc_type == QASettingActivity_.CALC_TYPE_FORMALU) {
			mSampleListView.setVisibility(View.INVISIBLE);
			mFormaluTextView.setVisibility(View.VISIBLE);
			mCalcTypeTextView.setText(getString(R.string.formalu_fitting));

			String showString = "CONC = ";
			float kk0 = Utils.getFloat2(k0);
			float kk1 = Utils.getFloat2(k1);
			float kk2 = Utils.getFloat2(k2);
			float kk3 = Utils.getFloat2(k3);

			if (kk0 != 0) {
				showString += kk0;
			}
			if (kk1 != 0) {
				if (kk0 != 0) {
					showString += " + ";
				}
				showString += kk1 + " x " + "A";
			}
			if (kk2 != 0) {
				if (kk0 != 0 || (kk1 != 0)) {
					showString += " + ";
				}
				showString += kk2 + " x " + "A²";
			}
			if (kk3 != 0) {
				if (kk0 != 0 || (kk1 != 0) || (kk2 != 0)) {
					showString += " + ";
				}
				showString += kk3 + " x " + "A³";
			}
			mFormaluTextView.setText(showString);
			mSampleData.clear();
			mSampleAdapter.notifyDataSetChanged();
			// draw chart
			mChart.clear();
			mChart.drawByFormalu(kk0, kk1, kk2, kk3);
			mChartView.postInvalidate();
		}

		String[] fittingMethodStrings = getResources().getStringArray(
				R.array.nihefangshi);
		mFittingMethodTextView.setText(fittingMethodStrings[fitting_method
				- QASettingActivity_.FITTING_METHOD_ONE_ZERO]);

		String[] concUnitStrings = getResources().getStringArray(
				R.array.nongdudanwei);
		mConcUnitTextView.setText(concUnitStrings[conc_unit
				- QASettingActivity_.CONCENTRATION_UNIT_UG_ML]);
		mChart.setYTitle(getString(R.string.conc)
				+ "("
				+ (concUnitStrings[conc_unit
						- QASettingActivity_.CONCENTRATION_UNIT_UG_ML]) + ")");
	}

	private void addOneTestItem(float abs) {
		Log.d(Contants.TAG, "add one item");
		float c = 0.00f;
		int calc_type = OnlabApplication.getInstance().getSpUtil()
				.getCalcType();
		if (calc_type == QASettingActivity_.CALC_TYPE_FORMALU) {
			c = k0 + k1 * abs + k2 * abs * abs + k3 * abs * abs * abs;
		} else {
			if (!isSampleDone) {
				mToastShow.toastShow("请先做样品标定");
				return;
			} else {
				c = sampleA0 + sampleA1 * abs;
			}
		}
		c = Utils.getFloat2(c);

		HashMap<String, String> item = new HashMap<String, String>();
		item.put("id", "" + (mTestData.size() + 1));
		item.put("name", "");
		if (OnlabApplication.getInstance().getSpUtil().isLowAccuracy()) {
			item.put("abs", String.format("%.3f", abs));
		} else {
			item.put("abs", String.format("%.4f", abs));
		}
		// fake conc data
		item.put("conc", "" + c);
		mTestData.add(item);
		mTestAdapter.add();
		mTestAdapter.notifyDataSetChanged();
		if (mTestData.size() > 0) {
			mTestListView.setSelection(mTestData.size() - 1);
		}
	}

	private void addEmptySample() {
		HashMap<String, String> item = new HashMap<String, String>();
		item.put("id", "" + (mSampleData.size() + 1));
		item.put("name", "");
		item.put("abs", "");
		item.put("conc", "");
		mSampleData.add(item);
		mSampleAdapter.add();
		mSampleAdapter.notifyDataSetChanged();
		if (mSampleData.size() > 0) {
			mSampleListView.setSelection(mSampleData.size() - 1);
		}
	}

	private void addOneItem(QuantitativeAnalysisRecord record) {
		HashMap<String, String> item = new HashMap<String, String>();
		item.put("id", "" + (mTestData.size() + 1));
		item.put("name", record.getName());
		if (OnlabApplication.getInstance().getSpUtil().isLowAccuracy()) {
			item.put("abs", String.format("%.3f", record.getAbs()));
		} else {
			item.put("abs", String.format("%.4f", record.getAbs()));
		}
		item.put("conc", "" + record.getConc());
		mTestData.add(item);
		mTestAdapter.notifyDataSetChanged();
		if (mTestData.size() > 0) {
			mTestListView.setSelection(mTestData.size() - 1);
		}
	}

	void removeOneItem(int pos) {
		mTestData.remove(pos);
		for (int i = 0; i < mTestData.size(); i++) {
			HashMap<String, String> item = mTestData.get(i);
			item.put("id", "" + (i + 1));
		}
		mTestAdapter.notifyDataSetChanged();
	}

	void removeSampleItem(int pos) {
		mSampleData.remove(pos);
		for (int i = 0; i < mSampleData.size(); i++) {
			HashMap<String, String> item = mSampleData.get(i);
			item.put("id", "" + (i + 1));
		}
		mSampleAdapter.notifyDataSetChanged();
	}

	public void setting() {
		mIntent.setClass(getActivity(), QASettingActivity_.class);
		mToastShow = new ToastShow(getActivity());
		mRequestCode = 0;
		startActivityForResult(mIntent, mRequestCode);
	}

	public void save() {
		String name = getString(R.string.quantitation_analysis_exp_string);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		name += format.format(new Date());
		mDialog.show();
		mDialog.setEditText(name);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_start:
			if (!mIsRezeroed) {
				mToastShow.toastShow(getString(R.string.notice_do_rezero));
				return;
			} else {
				MainActivity_ activity = (MainActivity_) getActivity();
				addOneTestItem(Utils.getFloat2(activity.getAbs()));
			}
			break;
		case R.id.btn_rezero:
			((MainActivity_) getActivity()).rezero();
			mIsRezeroed = true;
			break;

		case R.id.dialog_sample_ok_button:
			String name = mSampleDialog.getNameEditText();
			String conc = mSampleDialog.getConcEditText();
			String abss = (mSampleData.get(mSampleDialog.getIndex()))
					.get("abs");

			if (conc.length() < 1) {
				mToastShow.toastShow(getString(R.string.input_correct_conc));
				return;
			}
			HashMap<String, String> item = new HashMap<String, String>();
			item.put("id", "" + (mSampleDialog.getIndex() + 1));
			item.put("name", name);
			item.put("conc", conc);
			if (OnlabApplication.getInstance().getSpUtil().isLowAccuracy()) {
				item.put("abs", String.format("%.3f", abss));
			} else {
				item.put("abs", String.format("%.4f", abss));
			}
			mSampleData.set(mSampleDialog.getIndex(), item);
			mSampleAdapter.notifyDataSetChanged();
			mSampleDialog.dismiss();
			break;

		case R.id.dialog_sample_test_button:
			String name1 = mSampleDialog.getNameEditText();
			String conc1 = mSampleDialog.getConcEditText();
			if (conc1.length() < 1) {
				mToastShow.toastShow(getString(R.string.input_correct_conc));
				return;
			}
			HashMap<String, String> item1 = new HashMap<String, String>();
			item1.put("id", "" + (mSampleDialog.getIndex() + 1));
			item1.put("name", name1);
			item1.put("conc", conc1);
			// fake abs
			if (OnlabApplication.getInstance().getSpUtil().isLowAccuracy()) {
				item1.put("abs", String.format("%.3f", Utils
						.getFloat2(((MainActivity_) getActivity()).getAbs())));
			} else {
				item1.put("abs", String.format("%.4f", Utils
						.getFloat2(((MainActivity_) getActivity()).getAbs())));
			}

			mSampleData.set(mSampleDialog.getIndex(), item1);
			mSampleAdapter.notifyDataSetChanged();
			mSampleDialog.dismiss();

			String temp1 = mSampleData.get(mSampleData.size() - 1).get("abs");
			String temp2 = mSampleData.get(mSampleData.size() - 1).get("conc");
			if ((temp1.length() > 0) || (temp2.length() > 0)) {
				addEmptySample();
				mSampleAdapter.getIsSelected().put(mSampleDialog.getIndex(),
						true);
			}
			// float c = Float.parseFloat(conc1);
			// // fake abs
			// float abs = mSampleDialog.getIndex() + 1;
			// // add into chart
			// mChart.add(abs, c);
			// mChartView.postInvalidate();
			break;
		case R.id.dialog_sample_cancel_button:
			mSampleDialog.dismiss();
			break;

		case R.id.dialog_name_ok_button:
			name = mNameDialog.getNameEditText();
			conc = (mTestData.get(mNameDialog.getIndex())).get("conc");
			abss = (mTestData.get(mNameDialog.getIndex())).get("abs");

			item = new HashMap<String, String>();

			item.put("id", "" + (mSampleDialog.getIndex() + 1));
			item.put("name", name);
			item.put("conc", conc);
			if (OnlabApplication.getInstance().getSpUtil().isLowAccuracy()) {
				item.put("abs", String.format("%.3f", abss));
			} else {
				item.put("abs", String.format("%.4f", abss));
			}
			mTestData.set(mNameDialog.getIndex(), item);
			mTestAdapter.notifyDataSetChanged();
			mNameDialog.dismiss();
			break;

		case R.id.dialog_name_cancel_button:
			mNameDialog.dismiss();
			break;

		case R.id.dialog_save_button:
			String name2 = mDialog.getEditText();
			if (name2.length() < 1) {
				mToastShow.toastShow(getString(R.string.name_cannot_null));
			} else {
				// check the name is already availiable
				List<String> namesList = OnlabApplication.getInstance()
						.getQuantitativeAnalusisDB().getTables();
				for (int i = 0; i < namesList.size(); i++) {
					if (namesList.get(i).equals(name2)) {
						mToastShow
								.toastShow(getString(R.string.name_already_exist));
						return;
					}
				}

				String recordName = name2;
				for (int i = 0; i < mTestData.size(); i++) {
					int testIndex = 0;
					String testName = "";
					float testAbs = 0.0f;
					float testConc = 0.0f;
					long date = 0;

					HashMap<String, String> map = mTestData.get(i);
					testIndex = Integer.parseInt(map.get("id"));
					testName = map.get("name");
					testAbs = Float.parseFloat(map.get("abs"));
					testConc = Float.parseFloat(map.get("conc"));
					// skip date
					// date = Long.parseLong(map.get("date"));

					QuantitativeAnalysisRecord record = new QuantitativeAnalysisRecord(
							testIndex, testName, testAbs, testConc, date);
					OnlabApplication.getInstance().getQuantitativeAnalusisDB()
							.saveRecord(recordName, record);
				}
				mDialog.dismiss();
			}
			break;
		case R.id.dialog_cancel_button:
			mDialog.dismiss();
			break;

		case R.id.bt_select_all:
			HashMap<Integer, Boolean> sel = mTestAdapter.getIsSelected();
			for (int i = 0; i < sel.size(); i++) {
				sel.put(i, true);
			}
			mTestAdapter.notifyDataSetInvalidated();
			break;
		case R.id.bt_cancel:
			sel = mTestAdapter.getIsSelected();
			for (int i = 0; i < sel.size(); i++) {
				sel.put(i, false);
			}
			mTestAdapter.notifyDataSetInvalidated();
			break;
		case R.id.bt_delete:
			showTestDeleteDialog();
			// sel = mTestAdapter.getIsSelected();
			// int delCount = 0;
			// HashMap<Integer, Integer> delHashMap = new HashMap<Integer,
			// Integer>();
			// for (int i = 0; i < sel.size(); i++) {
			// if (sel.get(i)) {
			// delHashMap.put(delCount, i);
			// delCount = delCount + 1;
			// }
			// }
			// for (int i = 0; i < delCount; i++) {
			// removeOneItem(delHashMap.get(i));
			// sel = mTestAdapter.getIsSelected();
			// for (int j = delHashMap.get(i); j < sel.size() - 1; j++) {
			// sel.put(j, sel.get(j + 1));
			// }
			// sel.remove(sel.size() - 1);
			// for (int j = 0; j < delHashMap.size(); j++) {
			// delHashMap.put(j, delHashMap.get(j) - 1);
			// }
			// mTestAdapter.setIsSelected(sel);
			// }

			break;
		case R.id.bt_do_fitting:
			// do fitting
			sel = mSampleAdapter.getIsSelected();
			int fittingCount = 0;
			for (int i = 0; i < sel.size(); i++) {
				if (sel.get(i)) {
					String absVal = mSampleData.get(i).get("abs");
					String concVal = mSampleData.get(i).get("conc");
					if (absVal.length() > 0 && (concVal.length() > 0)) {
						fittingCount = fittingCount + 1;
					}
				}
			}

			Log.d(Contants.TAG, "fittingCount = " + fittingCount);
			double[] x = new double[fittingCount];
			double[] y = new double[fittingCount];
			int index = 0;
			for (int i = 0; i < sel.size(); i++) {
				if (sel.get(i)) {
					String absVal = mSampleData.get(i).get("abs");
					String concVal = mSampleData.get(i).get("conc");
					if (absVal.length() > 0 && (concVal.length() > 0)) {
						x[index] = Double.parseDouble(absVal);
						y[index] = Double.parseDouble(concVal);
						index = index + 1;
					}
				}
			}

			float xi2 = 0;
			float yi = 0;
			float xi = 0;
			float xiyi = 0;

			float a0;
			float a1;
			for (int i = 0; i < x.length; i++) {
				xi2 = (float) (xi2 + x[i] * x[i]);
				yi = (float) (yi + y[i]);
				xi = (float) (xi + x[i]);
				xiyi = (float) (xiyi + x[i] * y[i]);
			}

			a0 = (xi2 * yi - xi * xiyi) / (x.length * xi2 - xi * xi);
			a1 = (x.length * xiyi - xi * yi) / (x.length * xi2 - xi * xi);
			sampleA0 = a0;
			sampleA1 = a1;
			Log.d(Contants.TAG, "a0 = " + a0 + ", a1 = " + a1);

			String temp = "CONC = ";
			if (a0 != 0) {
				temp += "" + Utils.getFloat2(a0);
			}
			if (a1 != 0) {
				temp += " + " + Utils.getFloat2(a1) + " x " + "A";
			}
			mRValueTextView.setText(temp);

			mChart.clear();
			mChart.drawByFormalu(a0, a1, 0, 0);
			mChart.drawPoint(x, y);
			mChartView = mChart.getChartView(getActivity());
			mQAChart.removeAllViews();
			mQAChart.addView(mChartView);
			isSampleDone = true;
			break;
		case R.id.bt_sample_all_select:
			sel = mSampleAdapter.getIsSelected();
			for (int i = 0; i < sel.size() - 1; i++) {
				sel.put(i, true);
			}
			mSampleAdapter.notifyDataSetInvalidated();
			break;
		case R.id.bt_sample_delete:
			showSampleDeleteDialog();
			// sel = mSampleAdapter.getIsSelected();
			// delCount = 0;
			// delHashMap = new HashMap<Integer, Integer>();
			// for (int i = 0; i < sel.size(); i++) {
			// if (sel.get(i)) {
			// delHashMap.put(delCount, i);
			// delCount = delCount + 1;
			// }
			// }
			// for (int i = 0; i < delCount; i++) {
			// if (delHashMap.get(i) == (mSampleData.size() - 1)) {
			// continue;
			// }
			// removeSampleItem(delHashMap.get(i));
			// sel = mSampleAdapter.getIsSelected();
			// for (int j = delHashMap.get(i); j < sel.size() - 1; j++) {
			// sel.put(j, sel.get(j + 1));
			// }
			// sel.remove(sel.size() - 1);
			// for (int j = 0; j < delHashMap.size(); j++) {
			// delHashMap.put(j, delHashMap.get(j) - 1);
			// }
			// mSampleAdapter.setIsSelected(sel);
			// }
			break;
		default:
			break;
		}
	}

	private void showTestDeleteDialog() {
		new AlertDialog.Builder(getActivity())
				.setTitle(getString(R.string.system_notice))
				.setMessage(getString(R.string.sure_to_delete))
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								HashMap<Integer, Boolean> sel = mTestAdapter
										.getIsSelected();
								int delCount = 0;
								HashMap<Integer, Integer> delHashMap = new HashMap<Integer, Integer>();
								for (int i = 0; i < sel.size(); i++) {
									if (sel.get(i)) {
										delHashMap.put(delCount, i);
										delCount = delCount + 1;
									}
								}
								for (int i = 0; i < delCount; i++) {
									removeOneItem(delHashMap.get(i));
									sel = mTestAdapter.getIsSelected();
									for (int j = delHashMap.get(i); j < sel
											.size() - 1; j++) {
										sel.put(j, sel.get(j + 1));
									}
									sel.remove(sel.size() - 1);
									for (int j = 0; j < delHashMap.size(); j++) {
										delHashMap.put(j, delHashMap.get(j) - 1);
									}
									mTestAdapter.setIsSelected(sel);
								}
							}
						})
				.setNegativeButton(getString(R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
							}
						}).show();
	}

	private void showSampleDeleteDialog() {
		new AlertDialog.Builder(getActivity())
				.setTitle(getString(R.string.system_notice))
				.setMessage(getString(R.string.sure_to_delete))
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								HashMap<Integer, Boolean> sel = mSampleAdapter
										.getIsSelected();
								int delCount = 0;
								HashMap<Integer, Integer> delHashMap = new HashMap<Integer, Integer>();
								for (int i = 0; i < sel.size(); i++) {
									if (sel.get(i)) {
										delHashMap.put(delCount, i);
										delCount = delCount + 1;
									}
								}
								for (int i = 0; i < delCount; i++) {
									if (delHashMap.get(i) == (mSampleData
											.size() - 1)) {
										continue;
									}
									removeSampleItem(delHashMap.get(i));
									sel = mSampleAdapter.getIsSelected();
									for (int j = delHashMap.get(i); j < sel
											.size() - 1; j++) {
										sel.put(j, sel.get(j + 1));
									}
									sel.remove(sel.size() - 1);
									for (int j = 0; j < delHashMap.size(); j++) {
										delHashMap.put(j, delHashMap.get(j) - 1);
									}
									mSampleAdapter.setIsSelected(sel);
								}
							}
						})
				.setNegativeButton(getString(R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
							}
						}).show();
	}

}
